package com.mycity.controller;

import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mycity.bean.Post;
import com.mycity.bean.User;
import com.mycity.services.LoginService;
import com.mycity.services.ProfileService;
import com.mycity.services.RegistrationService;


@Controller
@RequestMapping("/services/user")
public class UserController extends HelloController{

	private RegistrationService registrationService = new RegistrationService();
    private LoginService loginService = new LoginService();
    private ProfileService profileService = new ProfileService();
	// get log4j handler
	private static final Logger LOGGER = Logger.getLogger(UserController.class);
		
    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }


	public void setRegistrationService(RegistrationService registrationService) {
		this.registrationService = registrationService;
	}

	@RequestMapping(method = RequestMethod.GET, value = "/login")
	public @ResponseBody User loginUser(String email, String password) throws Exception {
        User loggedinUser;
	    try {
			loggedinUser = loginService.login(email, password);
			
			// Nullify the fields that need to be secure.
			loggedinUser.setPassword(null);
		} catch (Exception e) {
			LOGGER.error("The user cannot login : " + email, e);
			throw new Exception("Invalid username or password");
		} 

        return loggedinUser;

		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/register")
	public @ResponseBody User registerUser(String username, String name, String surname, String email, String password) throws Exception {
        User loggedinUser;
	    try {
			loggedinUser = registrationService.registerUser(username, name, surname, email, password);
			
			// Nullify the fields that need to be secure.
			loggedinUser.setPassword(null);
		} catch (Exception e) {
			LOGGER.error("The user cannot register : " + email, e);
			throw new Exception("Invalid username or password");
		} 

        return loggedinUser;

		
	}
	

	@RequestMapping(method = RequestMethod.GET, value = "/loginFailed")
	public @ResponseBody String loginFailed(String email, String password) throws Exception {

        return "Invalid username or password!";

		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/showAllPosts")
	public @ResponseBody List<Post> showAllPosts(int userId) throws Exception {

		List<Post> postList;
	    try {
	    	postList = profileService.getAllPostsByUserId(userId);
			
		} catch (Exception e) {
			LOGGER.error("The user has no post", e);
			throw(e);
		} 

        return postList;

		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/showRecentPosts")
	public @ResponseBody List<Post> showRecentPosts() throws Exception {

		List<Post> postList;
	    try {
	    	postList = profileService.showRecentPosts();
			
		} catch (Exception e) {
			throw(e);
		} 

        return postList;

		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/getPostByPostId")
	public @ResponseBody Post getPostByPostId(int postId) throws Exception {

		Post post;
	    try {
	    	post = profileService.getPostById(postId);
			
		} catch (Exception e) {
			throw(e);
		} 

        return post;

		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/post")
	public @ResponseBody int post(int userId, int postType, String postContent) throws Exception {

	    try {
	    	return profileService.post(userId, postType, postContent);

			
		} catch (Exception e) {
			return -1;
		} 


		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/emailAvailable")
	public @ResponseBody boolean emailAvailable(String email) throws Exception {

		boolean available;
	    try {
	    	available = registrationService.emailAvailable(email);
			
		} catch (Exception e) {
			LOGGER.error("The user has no post", e);
			throw(e);
		} 

        return available;

		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/usernameAvailable")
	public @ResponseBody boolean usernameAvailable(String username) throws Exception {

		boolean available;
	    try {
	    	available = registrationService.usernameAvailable(username);
			
		} catch (Exception e) {
			LOGGER.error("The user has no post", e);
			throw(e);
		} 
        return available;		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/uploadFile")
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/uploadFile")
    public @ResponseBody String uploadFile(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.flush();
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

    
}